/**
 * 
 */
package com.sys.console.common;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;


/**
 * 数据库的备份
 * 
 * @author zxp
 *
 */
public class DataBaseUtils {

	public static Properties getProperties() {
		try {
			Properties props = new Properties();
			props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties"));
			return props;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void exportDataBase() {

		Date now = new Date();
		DateFormat df = DateFormat.getDateTimeInstance();
		String dbName = df.format(now) + ".sql";
		dbName = dbName.replaceAll(":", "_");
		dbName = dbName.replaceAll(" ", "_");
		Properties pr = getProperties();
		//PropertiesUtil pr = new PropertiesUtil("jdbc.properties");
		String user = pr.getProperty("jdbc.username");
		String password = pr.getProperty("jdbc.password");
		String database = pr.getProperty("jdbc.database");
		String filepath = pr.getProperty("jdbc.backupPath") + dbName;

		// 创建执行的批处理
		FileOutputStream fout = null;
		OutputStreamWriter writer = null;
		try {
			String batFile = "//backup_databae.bat";
			fout = new FileOutputStream(batFile);
			writer = new OutputStreamWriter(fout, "utf8");
			StringBuffer sb = new StringBuffer("");
			sb.append(pr.getProperty("mysql.lumu") + " \r\n");
			sb.append("cd " + pr.getProperty("mysql.binPath") + " \r\n");
			sb.append("mysqldump -u " + user + " -p" + password + " " + database + " >" + filepath + "\r\n");
			sb.append("exit");
			String outStr = sb.toString();
			writer.write(outStr);
			writer.flush();
			writer.close();
			fout.close();

			Runtime.getRuntime().exec(" cmd /c start " + batFile);
			//logger.info("备份数据库成功！");
		} catch (IOException e) {
			e.printStackTrace();
			//logger.error("备份数据库失败！", e);
		} finally {
			writer = null;
			fout = null;
		}

	}
}
